const Base = require('./base.js');
const fs = require('fs');
const _ = require('lodash');

module.exports = class extends Base {
  async infoAction() {
    const userInfo = await this.model('user').where({id: this.getLoginUserId()}).find();
    const coupons = await this.model('user_coupon').where({user_id: this.getLoginUserId(), status: 0, gmt_end: ['>', Date.parse(new Date())]}).count();
    delete userInfo.password;
    userInfo.couponNum = coupons;
    return this.success(userInfo);
  }
  async balanceAction() {
    const userInfo = await this.model('user').where({id: this.getLoginUserId()}).field(['balance']).find();
    delete userInfo.password;
    return this.success(userInfo);
  }

  async bindAgentAction() {
    const id = this.get('id');
    if (this.getLoginUserId().toString() === id) {
      return this.fail('不能绑定自己');
    }
    const user = await this.model('user').where({id: this.getLoginUserId()}).find();
    if (!user.agent_id) {
      await this.model('user').where({id: this.getLoginUserId()}).update({
        agent_id: id
      });
    }
    return this.success();
  }

  /**
   * 保存用户头像
   * @returns {Promise.<void>}
   */
  async saveAvatarAction() {
    const avatar = this.file('avatar');
    if (think.isEmpty(avatar)) {
      return this.fail('保存失败');
    }

    const avatarPath = think.RESOURCE_PATH + `/static/user/avatar/${this.getLoginUserId()}.` + _.last(_.split(avatar.path, '.'));

    fs.rename(avatar.path, avatarPath, function(res) {
      return this.success();
    });
  }
  async rechargeSetAction() {
    const vipInfo = await this.model('user_level').select();
    return this.success(vipInfo);
  }
  // async rechargePayAction() {
  //   const id = this.get('id');
  //   const vipInfo = await this.model('user_level').where({id: id}).find();
  //   if (think.isEmpty(vipInfo)) {
  //     return this.fail('充值失败');
  //   }
  //   const userInfo = await this.model('user').where({ id: this.getLoginUserId() }).find();
  //   if (userInfo.vip && vipInfo.type === 2) {
  //     return this.fail('用户已经是会员');
  //   }
  //   const orderSn = this.model('order').generateOrderNumber();
  //   const WeixinSerivce = this.service('wxpay', 'api');
  //   await this.model('user_recharge').add({
  //     user_id: this.getLoginUserId(),
  //     recharge_no: orderSn,
  //     pay_price: vipInfo.money,
  //     level_id: id,
  //     level_type: vipInfo.type
  //   });
  //   try {
  //     const returnParams = await WeixinSerivce.createUnifiedVip({
  //       openid: userInfo.weixin_openid,
  //       body: '订单编号：' + orderSn,
  //       out_trade_no: orderSn,
  //       total_fee: vipInfo.money * 100,
  //       spbill_create_ip: this.ctx.ip
  //     });
  //     return this.success(returnParams);
  //   } catch (err) {
  //     return this.fail('微信支付失败');
  //   }
  // }
  async getCodeAction() {
    const WeixinServe = this.service('weixin', 'api');
    const cacheAccessToken = await this.cache('access_token');
    const img = await WeixinServe.getWxcode(cacheAccessToken, this.getLoginUserId());
    return this.success(img);
  }
  async couponAction() {
    const coupon = await this.model('user_coupon').where({user_id: this.getLoginUserId(), status: 0}).select();
    if (think.isEmpty(coupon)) {
      return this.success([]);
    }

    const couponIds = [];
    for (const item of coupon) {
      couponIds.push(item.coupon_id);
    }
    const originCoupon = await this.model('coupon').where({id: ['IN', couponIds]}).select();
    for (const item of coupon) {
      for (const coupons of originCoupon) {
        if (item.coupon_id === coupons.id) {
          item.info = coupons;
          if (item.gmt_end < Date.parse(new Date())) {
            item.status = 3;
            item.statusTxt = '已过期';
          }
        }
      }
    }
    const newCoupon = [];
    for (const item of coupon) {
      if (item.info && item.status !== 3) {
        newCoupon.push(item);
      }
    }
    return this.success(newCoupon);
  }
  /**
   * 预定
   * @returns {Promise.<void>}
   */
  async reserveAction() {
    const phone = this.post('phone');
    const num = this.post('num');
    const time = this.post('time');
    const user = this.post('user');
    const name = this.post('name');

    const userInfo = await this.model('user').where({ id: user }).find();

    let money = 0;

    if (num > 3) {
      money = num * 100000;
    }

    const reserveSn = this.model('order').generateOrderNumber();

    const reserveId = await this.model('user_reserve').add({
      phone: phone,
      num: num,
      time: time,
      name: name,
      reserve_sn: reserveSn,
      money: money / 100,
      user_id: user,
      user_type: userInfo.type
    });
    if (num < 4) {
      return this.success({
        reserveId: reserveId
      });
    }

    const WeixinSerivce = this.service('wxpay', 'api');
    try {
      const returnParams = await WeixinSerivce.createUnifiedReserve({
        openid: userInfo.weixin_openid,
        body: '订单编号：' + reserveSn,
        out_trade_no: reserveSn,
        total_fee: money,
        spbill_create_ip: this.ctx.ip
      });
      returnParams.reserveId = reserveId;

      return this.success(returnParams);
    } catch (err) {
      return this.fail('微信支付失败');
    }
  }
};
